package JSF;

import Entidades.DocAdjunto;
import Entidades.Estado;
import Entidades.Expediente;
import Entidades.Trabajador;
import JSF.util.JsfUtil;
import JSF.util.PaginationHelper;
import SessionB.DocAdjuntoFacade;
import java.io.IOException;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.ActionEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import org.primefaces.context.RequestContext;

@Named("docAdjuntoController")
@SessionScoped
public class DocAdjuntoController implements Serializable {

    private DocAdjunto current;
    private DocAdjunto docadjunto;
    private List<DocAdjunto> lista;
    private String idregistro;
    private Trabajador trabajador;
    private String cadena_conexion = "jdbc:mysql://localhost:3306/emilima_tradoc";
    private String password = "carloscd3";
    private static Connection conn = null;
    private DataModel items = null;
    @EJB
    private SessionB.DocAdjuntoFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;

    public DocAdjuntoController() {
    }

    public DocAdjunto getSelected() {
        if (current == null) {
            current = new DocAdjunto();
            selectedItemIndex = -1;
        }
        return current;
    }

    private DocAdjuntoFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    //****************************************************************
    public List<DocAdjunto> getLista() {
        return lista;
    }

    public void setLista(List<DocAdjunto> lista) {
        this.lista = lista;
    }

    public DocAdjunto getDocadjunto() {
        return docadjunto;
    }

    public void setDocadjunto(DocAdjunto docadjunto) {
        this.docadjunto = docadjunto;
    }

    public String getIdregistro() {
        return idregistro;
    }

    public void setIdregistro(String idregistro) {
        this.idregistro = idregistro;
    }

    public Trabajador getTrabajador() {
        return trabajador;
    }

    public void setTrabajador(Trabajador trabajador) {
        this.trabajador = trabajador;
    }

    public void filtrar_nRegistro() {   // Filtra los Expedientes del Dia 
        System.out.println(" ------- En filtrar_nRegistro() Adjuntar ...");
        lista = new LinkedList<DocAdjunto>();
        for (DocAdjunto me : ejbFacade.findAll()) {
            //           System.out.println("me.getExpediente(). : "+me.getExpediente().getCodExp());  
            if (me.getExpediente().getCodExp().equals(idregistro)) {
//            if (v.getFechaReg().equals(fecha_emision)) { && v.getEstado().getIdEstado().equals("01")
                lista.add(me);
            }
        }

    }

    public void prepareCreateDocAdj() {
        docadjunto = new DocAdjunto();
        current = new DocAdjunto();
    }

    public String grabaDocAdj() {
        try {
            docadjunto.setIdDocAdj(5);
            Estado est = new Estado();
            est.setIdEstado("01");
            Date utilDate = new java.util.Date();
            long lnMilisegundos = utilDate.getTime();
            Timestamp fechahora = new java.sql.Timestamp(lnMilisegundos);
            docadjunto.setFechIngre(fechahora);
             Expediente exped = new Expediente();
            exped.setCodExp(idregistro);
            docadjunto.setExpediente(exped);
            docadjunto.setEstado(est);
            current = docadjunto;
            ejbFacade.create(current);
      
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, " Registro Procesado ..!", "Se Agrego Registro Correctamente");
            RequestContext.getCurrentInstance().showMessageInDialog(message);
        } catch (Exception e) {
            e.printStackTrace();
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, " Error en Registro ..!", "No Agrego Registro ");
            RequestContext.getCurrentInstance().showMessageInDialog(message);
        }
        return null;
    }

    public String eliminaDocAdj() {
        try {
            System.out.println(" ------ Antes de Eliminar Doc Adjunto ...");
            ejbFacade.remove(docadjunto);
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, " Eliminación Procesada ..!", "Registro Eliminado Correctamente");
            RequestContext.getCurrentInstance().showMessageInDialog(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

        JasperPrint jasperPrint;
    public void initov2() throws JRException {
        try {
            conn = (Connection) DriverManager.getConnection(cadena_conexion, "root", password);
            conn.setAutoCommit(false);
            String idCliente = idregistro; //  expedient.getCodExp().toString();
            Map parameters = new HashMap();
            parameters.put("P_IdReg", idCliente);
            String reportPath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/reports/DocAdjuntos.jasper");
            jasperPrint = JasperFillManager.fillReport(reportPath, parameters, conn);
        } catch (Exception e) {
        }
    }
 
    public void docAjuntPrn(ActionEvent actionEvent) throws JRException, IOException {
        initov2();
        HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        String fileNa = "DocAdjuntos";
        httpServletResponse.addHeader("Content-disposition", "inline; filename=\"" + fileNa + "\"");
        ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
        FacesContext.getCurrentInstance().responseComplete();
    }

    
    
//****************************************************************    
    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (DocAdjunto) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new DocAdjunto();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("DocAdjuntoCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (DocAdjunto) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            current = docadjunto;
            getFacade().edit(current);
            //       JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("EditoOk"));
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, " Moficiación Procesada ..!", "Registro Modificado Correctamente");
            RequestContext.getCurrentInstance().showMessageInDialog(message);
            System.out.println(" modifico Doc Adjunt");
        } catch (Exception e) {
//            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, " Error en Moficiación ..!", "No se realizo Modificado "+e);
//            RequestContext.getCurrentInstance().showMessageInDialog(message);
            System.out.println(" No modifico DocAdjunt");
            e.printStackTrace();
            //JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("EditoMal"));
        }
        return null;
    }

    public String updateOrig() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("DocAdjuntoUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (DocAdjunto) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("DocAdjuntoDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public DocAdjunto getDocAdjunto(java.lang.Integer id) {
        return ejbFacade.find(id);
    }

    @FacesConverter(forClass = DocAdjunto.class)
    public static class DocAdjuntoControllerConverter implements Converter {

        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            DocAdjuntoController controller = (DocAdjuntoController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "docAdjuntoController");
            return controller.getDocAdjunto(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuilder sb = new StringBuilder();
            sb.append(value);
            return sb.toString();
        }

        @Override
        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof DocAdjunto) {
                DocAdjunto o = (DocAdjunto) object;
                return getStringKey(o.getIdDocAdj());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + DocAdjunto.class.getName());
            }
        }
    }
}
